import React, { useState, useEffect, useMemo, useCallback } from 'react';
import axios from 'axios';
import { Modal, Form, Input, Select, DatePicker, message, Pagination, Skeleton } from 'antd';
import dayjs from 'dayjs';
import { log } from 'console';

interface Ad {
  _id?: string;
  id?: number;
  title: string;
  type: '轮播图' | '弹窗' | '横幅' | '推荐位';
  link: string;
  status: '活跃' | '已暂停' | '已结束';
  startDate: string;
  endDate: string;
  views: number;
  clicks: number;
}

interface PaginationData {
  total: number;
  page: number;
  pageSize: number;
}

const { Option } = Select;
const { RangePicker } = DatePicker;

const API_BASE_URL = 'http://localhost:3000/LCY';

// 默认分页大小
const DEFAULT_PAGE_SIZE = 10;

const Ads: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'all' | 'active' | 'paused' | 'ended'>('all');
  const [adList, setAdList] = useState<Ad[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [currentAd, setCurrentAd] = useState<Ad | null>(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState<PaginationData>({
    total: 0,
    page: 1,
    pageSize: DEFAULT_PAGE_SIZE
  });
  
  // 获取广告列表
  const fetchAds = useCallback(async (page = 1, status?: string) => {
    try {
      setIsLoading(true);
      
      // 构建查询参数
      const params: Record<string, any> = {
        page,
        pageSize: pagination.pageSize
      };
      
      // 根据选项卡状态添加状态过滤
      if (status) {
        params.status = status;
      }
      
      const response: any = await axios.get(`${API_BASE_URL}/ads`, { params });
      console.log();
      
      if (response.data.code === 200) {
        // 确保日期格式正确
        const formattedData = response.data.data.items.map((item: any) => ({
          ...item,
          startDate: item.startDate ? item.startDate.split('T')[0] : '',
          endDate: item.endDate ? item.endDate.split('T')[0] : ''
        }));
        console.log(formattedData);
        
        setAdList(formattedData);
        setPagination({
          total: response.data.data.total,
          page: response.data.data.page,
          pageSize: response.data.data.pageSize
        });
      } else {
        message.error('获取广告列表失败');
      }
    } catch (error) {
      console.error('获取广告列表失败', error);
      message.error('获取广告列表失败');
    } finally {
      setIsLoading(false);
    }
  }, [pagination.pageSize]);
  
  // 根据标签切换状态
  useEffect(() => {
    const statusMap = {
      all: '',
      active: '活跃',
      paused: '已暂停',
      ended: '已结束'
    };
    fetchAds(1, activeTab !== 'all' ? statusMap[activeTab] : undefined);
  }, [activeTab, fetchAds]);
  
  // 处理页码变化
  const handlePageChange = (page: number) => {
    const statusMap = {
      all: '',
      active: '活跃',
      paused: '已暂停',
      ended: '已结束'
    };
    fetchAds(page, activeTab !== 'all' ? statusMap[activeTab] : undefined);
  };
  
  // 添加或编辑广告
  const handleAddOrEditAd = () => {
    setIsEdit(false);
    setCurrentAd(null);
    form.resetFields();
    
    // 设置默认日期范围为当前日期开始的7天
    const today = dayjs();
    const nextWeek = dayjs().add(7, 'day');
    form.setFieldsValue({
      date: [today, nextWeek]
    });
    
    setIsModalVisible(true);
  };
  
  // 编辑广告
  const handleEditAd = (ad: Ad) => {
    setIsEdit(true);
    setCurrentAd(ad);
    form.setFieldsValue({
      title: ad.title,
      type: ad.type,
      link: ad.link,
      date: [
        dayjs(ad.startDate, 'YYYY-MM-DD'),
        dayjs(ad.endDate, 'YYYY-MM-DD')
      ]
    });
    setIsModalVisible(true);
  };
  
  // 查看广告详情（只读）
  const handleViewAd = (ad: Ad) => {
    setCurrentAd(ad);
    Modal.info({
      title: '广告详情',
      width: 600,
      content: (
        <div className="ad-detail">
          <p><strong>标题：</strong> {ad.title}</p>
          <p><strong>类型：</strong> {ad.type}</p>
          <p><strong>状态：</strong> {ad.status}</p>
          <p><strong>展示期：</strong> {ad.startDate} 至 {ad.endDate}</p>
          <p><strong>曝光量：</strong> {ad.views?.toLocaleString() ?? "0"}</p>
          <p><strong>点击量：</strong> {ad.clicks?.toLocaleString() ?? "0"}</p>
          <p><strong>转化率：</strong> {ad.views > 0 ? ((ad.clicks / ad.views) * 100).toFixed(2) : '0.00'}%</p>
          <p><strong>链接：</strong> <a href={ad.link} target="_blank" rel="noopener noreferrer">{ad.link}</a></p>
        </div>
      ),
      onOk() {},
    });
  };
  
  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const formData = {
        title: values.title,
        type: values.type,
        link: values.link,
        startDate: values.date[0].format('YYYY-MM-DD'),
        endDate: values.date[1].format('YYYY-MM-DD'),
        status: '活跃',
        views: 0,
        clicks: 0
      };
      
      if (isEdit && currentAd?._id) {
        // 编辑时保留原始的浏览量和点击量数据
        formData.views = currentAd.views;
        formData.clicks = currentAd.clicks;
        formData.status = currentAd.status;
        
        // 更新广告
        const response = await axios.put(`${API_BASE_URL}/ads/${currentAd._id}`, formData);
        if ((response.data as any).code === 200) {
          message.success('更新广告成功');
          
          // 重新加载当前页数据
          const statusMap = {
            all: '',
            active: '活跃',
            paused: '已暂停',
            ended: '已结束'
          };
          fetchAds(pagination.page, activeTab !== 'all' ? statusMap[activeTab] : undefined);
          
          setIsModalVisible(false);
        } else {
          message.error('更新广告失败');
        }
      } else {
        // 创建广告
        const response = await axios.post(`${API_BASE_URL}/ads`, formData);
        if ((response.data as any).code === 201) {
          message.success('创建广告成功');
          
          // 重新加载第一页数据
          const statusMap = {
            all: '',
            active: '活跃',
            paused: '已暂停',
            ended: '已结束'
          };
          fetchAds(1, activeTab !== 'all' ? statusMap[activeTab] : undefined);
          
          setIsModalVisible(false);
        } else {
          message.error('创建广告失败');
        }
      }
    } catch (error) {
      console.error('提交表单失败', error);
      message.error('提交表单失败，请检查输入');
    }
  };
  
  // 更新广告状态
  const handleStatusChange = async (ad: Ad, newStatus: '活跃' | '已暂停' | '已结束') => {
    try {
      const response = await axios.patch(`${API_BASE_URL}/ads/${ad._id}/status`, { status: newStatus });
      if ((response.data as any).code === 200) {
        message.success(`广告已${newStatus === '活跃' ? '启用' : '暂停'}`);
        
        // 重新加载当前页数据
        const statusMap = {
          all: '',
          active: '活跃',
          paused: '已暂停',
          ended: '已结束'
        };
        fetchAds(pagination.page, activeTab !== 'all' ? statusMap[activeTab] : undefined);
      } else {
        message.error('操作失败');
      }
    } catch (error) {
      console.error('更新状态失败', error);
      message.error('更新状态失败');
    }
  };
  
  // 删除广告
  const handleDeleteAd = async (adId: string) => {
    try {
      const response = await axios.delete(`${API_BASE_URL}/ads/${adId}`);
      if ((response.data as any).code === 200) {
        message.success('删除广告成功');
        
        // 重新加载当前页数据，如果当前页已经没有数据，则加载上一页
        const statusMap = {
          all: '',
          active: '活跃',
          paused: '已暂停',
          ended: '已结束'
        };
        
        // 如果当前页只有一条数据，删除后应该加载上一页
        if (adList.length === 1 && pagination.page > 1) {
          fetchAds(pagination.page - 1, activeTab !== 'all' ? statusMap[activeTab] : undefined);
        } else {
          fetchAds(pagination.page, activeTab !== 'all' ? statusMap[activeTab] : undefined);
        }
      } else {
        message.error('删除广告失败');
      }
    } catch (error) {
      console.error('删除广告失败', error);
      message.error('删除广告失败');
    }
  };
  
  // 广告状态统计
  const statsData = useMemo(() => {
    return {
      total: adList.length,
      active: adList.filter(ad => ad.status === '活跃').length,
      views: adList.reduce((sum, ad) => sum + ad.views, 0),
      clicks: adList.reduce((sum, ad) => sum + ad.clicks, 0),
      rate: adList.reduce((sum, ad) => sum + ad.views, 0) > 0 
        ? (adList.reduce((sum, ad) => sum + ad.clicks, 0) / 
          adList.reduce((sum, ad) => sum + ad.views, 0) * 100).toFixed(2)
        : '0.00'
    };
  }, [adList]);

  return (
    <div className="page-container">
      <h1>广告管理</h1>
      
      <div className="actions-bar">
        <button className="btn btn-primary" onClick={handleAddOrEditAd}>添加广告</button>
        <div className="tab-filters">
          <button 
            className={`tab-btn ${activeTab === 'all' ? 'active' : ''}`}
            onClick={() => setActiveTab('all')}
            style={{ 
              padding: '8px 16px', 
              margin: '0 5px', 
              borderRadius: '4px',
              border: '1px solid #ddd',
              backgroundColor: activeTab === 'all' ? '#1890ff' : '#f0f0f0',
              color: activeTab === 'all' ? 'white' : '#333',
              cursor: 'pointer',
              transition: 'all 0.3s'
            }}
          >
            全部
          </button>
          <button 
            className={`tab-btn ${activeTab === 'active' ? 'active' : ''}`}
            onClick={() => setActiveTab('active')}
            style={{ 
              padding: '8px 16px', 
              margin: '0 5px', 
              borderRadius: '4px',
              border: '1px solid #ddd',
              backgroundColor: activeTab === 'active' ? '#52c41a' : '#f0f0f0',
              color: activeTab === 'active' ? 'white' : '#333',
              cursor: 'pointer',
              transition: 'all 0.3s'
            }}
          >
            活跃
          </button>
          <button 
            className={`tab-btn ${activeTab === 'paused' ? 'active' : ''}`}
            onClick={() => setActiveTab('paused')}
            style={{ 
              padding: '8px 16px', 
              margin: '0 5px', 
              borderRadius: '4px',
              border: '1px solid #ddd',
              backgroundColor: activeTab === 'paused' ? '#faad14' : '#f0f0f0',
              color: activeTab === 'paused' ? 'white' : '#333',
              cursor: 'pointer',
              transition: 'all 0.3s'
            }}
          >
            已暂停
          </button>
          <button 
            className={`tab-btn ${activeTab === 'ended' ? 'active' : ''}`}
            onClick={() => setActiveTab('ended')}
            style={{ 
              padding: '8px 16px', 
              margin: '0 5px', 
              borderRadius: '4px',
              border: '1px solid #ddd',
              backgroundColor: activeTab === 'ended' ? '#ff4d4f' : '#f0f0f0',
              color: activeTab === 'ended' ? 'white' : '#333',
              cursor: 'pointer',
              transition: 'all 0.3s'
            }}
          >
            已结束
          </button>
        </div>
      </div>
      
      <div className="table-container">
        {isLoading ? (
          <div className="loading-container" style={{ padding: '20px' }}>
            <Skeleton active paragraph={{ rows: 5 }} />
          </div>
        ) : adList.length > 0 ? (
        <table className="data-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>标题</th>
              <th>类型</th>
              <th>状态</th>
              <th>展示期</th>
              <th>曝光量</th>
              <th>点击量</th>
              <th>转化率</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
              {adList.map(ad => (
                <tr key={ad._id}>
                  <td>{ad._id ? ad._id.slice(-6) : ad.id}</td>
                <td>{ad.title}</td>
                <td>{ad.type}</td>
                <td>
                  <span className={`status-badge ${
                    ad.status === '活跃' ? 'success' : 
                    ad.status === '已暂停' ? 'warning' : 
                    'inactive'
                    }`}
                    style={{
                      padding: '4px 8px',
                      borderRadius: '12px',
                      fontSize: '12px',
                      fontWeight: 'bold',
                      backgroundColor: ad.status === '活跃' ? '#e6f7ff' : 
                                      ad.status === '已暂停' ? '#fff7e6' : '#fff1f0',
                      color: ad.status === '活跃' ? '#1890ff' : 
                              ad.status === '已暂停' ? '#fa8c16' : '#f5222d',
                      border: `1px solid ${
                        ad.status === '活跃' ? '#91caff' : 
                        ad.status === '已暂停' ? '#ffd591' : '#ffa39e'
                      }`
                    }}>
                    {ad.status}
                  </span>
                </td>
                <td>{ad.startDate} 至 {ad.endDate}</td>
                <td>{ad.views?.toLocaleString() ?? "0"}</td>
                <td>{ad.clicks?.toLocaleString() ?? "0"}</td>
                  <td>{ad.views > 0 ? ((ad.clicks / ad.views) * 100).toFixed(2) : '0.00'}%</td>
                  <td>
                    <button 
                      className="btn btn-view" 
                      onClick={() => handleViewAd(ad)}
                      style={{ 
                        padding: '5px 10px', 
                        marginRight: '5px',
                        backgroundColor: '#1890ff',
                        color: 'white',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: 'pointer'
                      }}
                    >
                      查看
                    </button>
                    {ad.status !== '已结束' && (
                      <button 
                        className="btn btn-edit" 
                        onClick={() => handleEditAd(ad)}
                        style={{ 
                          padding: '5px 10px', 
                          marginRight: '5px',
                          backgroundColor: '#52c41a',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer'
                        }}
                      >
                        编辑
                      </button>
                    )}
                  {ad.status === '活跃' ? (
                      <button 
                        className="btn btn-pause" 
                        onClick={() => handleStatusChange(ad, '已暂停')}
                        style={{ 
                          padding: '5px 10px', 
                          marginRight: '5px',
                          backgroundColor: '#faad14',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer'
                        }}
                      >
                        暂停
                      </button>
                  ) : ad.status === '已暂停' ? (
                      <button 
                        className="btn btn-activate"
                        onClick={() => handleStatusChange(ad, '活跃')}
                        style={{ 
                          padding: '5px 10px', 
                          marginRight: '5px',
                          backgroundColor: '#13c2c2',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer'
                        }}
                      >
                        启用
                      </button>
                  ) : null}
                    <button 
                      className="btn btn-delete" 
                      onClick={() => handleDeleteAd(ad._id as string)}
                      style={{ 
                        padding: '5px 10px',
                        backgroundColor: '#ff4d4f',
                        color: 'white',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: 'pointer'
                      }}
                    >
                      删除
                    </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        ) : (
          <div className="empty-data" style={{ textAlign: 'center', padding: '40px 0' }}>
            暂无广告数据
          </div>
        )}
        
        {/* 分页器 */}
        {pagination.total > 0 && (
          <div className="pagination-container" style={{ marginTop: '20px', textAlign: 'right' }}>
            <Pagination
              current={pagination.page}
              total={pagination.total}
              pageSize={pagination.pageSize}
              onChange={handlePageChange}
              showSizeChanger={false}
              showTotal={(total) => `共 ${total} 条数据`}
            />
          </div>
        )}
      </div>
      
      {/* 改进后的指标摘要样式 */}
      <div className="metrics-summary" style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap: '20px',
        marginTop: '30px',
        justifyContent: 'space-between'
      }}>
        <div className="metric-card" style={{
          flex: '1',
          minWidth: '200px',
          padding: '20px',
          borderRadius: '10px',
          backgroundColor: '#f0f7ff',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
          transition: 'all 0.3s ease',
          border: '1px solid #d6e4ff',
          textAlign: 'center'
        }}>
          <h3 style={{ 
            color: '#1890ff', 
            fontSize: '16px', 
            marginBottom: '10px',
            fontWeight: '500'
          }}>广告总数</h3>
          <div className="metric-value" style={{ 
            fontSize: '28px', 
            fontWeight: 'bold',
            color: '#262626'
          }}>{pagination.total}</div>
        </div>
        
        <div className="metric-card" style={{
          flex: '1',
          minWidth: '200px',
          padding: '20px',
          borderRadius: '10px',
          backgroundColor: '#f6ffed',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
          transition: 'all 0.3s ease',
          border: '1px solid #d9f7be',
          textAlign: 'center'
        }}>
          <h3 style={{ 
            color: '#52c41a', 
            fontSize: '16px', 
            marginBottom: '10px',
            fontWeight: '500'
          }}>活跃广告</h3>
          <div className="metric-value" style={{ 
            fontSize: '28px', 
            fontWeight: 'bold',
            color: '#262626'
          }}>{statsData.active}</div>
        </div>
        
        <div className="metric-card" style={{
          flex: '1',
          minWidth: '200px',
          padding: '20px',
          borderRadius: '10px',
          backgroundColor: '#e6fffb',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
          transition: 'all 0.3s ease',
          border: '1px solid #b5f5ec',
          textAlign: 'center'
        }}>
          <h3 style={{ 
            color: '#13c2c2', 
            fontSize: '16px', 
            marginBottom: '10px',
            fontWeight: '500'
          }}>总曝光量</h3>
          <div className="metric-value" style={{ 
            fontSize: '28px', 
            fontWeight: 'bold',
            color: '#262626'
          }}>{statsData.views?.toLocaleString() ?? "0"}</div>
        </div>
        
        <div className="metric-card" style={{
          flex: '1',
          minWidth: '200px',
          padding: '20px',
          borderRadius: '10px',
          backgroundColor: '#fff2e8',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
          transition: 'all 0.3s ease',
          border: '1px solid #ffd8bf',
          textAlign: 'center'
        }}>
          <h3 style={{ 
            color: '#fa8c16', 
            fontSize: '16px', 
            marginBottom: '10px',
            fontWeight: '500'
          }}>总点击量</h3>
          <div className="metric-value" style={{ 
            fontSize: '28px', 
            fontWeight: 'bold',
            color: '#262626'
          }}>{statsData.clicks.toLocaleString()}</div>
        </div>
        
        <div className="metric-card" style={{
          flex: '1',
          minWidth: '200px',
          padding: '20px',
          borderRadius: '10px',
          backgroundColor: '#f9f0ff',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
          transition: 'all 0.3s ease',
          border: '1px solid #efdbff',
          textAlign: 'center'
        }}>
          <h3 style={{ 
            color: '#722ed1', 
            fontSize: '16px', 
            marginBottom: '10px',
            fontWeight: '500'
          }}>平均转化率</h3>
          <div className="metric-value" style={{ 
            fontSize: '28px', 
            fontWeight: 'bold',
            color: '#262626'
          }}>{statsData.rate}%</div>
        </div>
      </div>
      
      <Modal
        title={isEdit ? "编辑广告" : "添加广告"}
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={() => setIsModalVisible(false)}
        okText={isEdit ? "更新" : "添加"}
        cancelText="取消"
        maskClosable={false}
        destroyOnHidden={true}
      >
        <Form form={form} layout="vertical">
          <Form.Item 
            name="title" 
            label="广告标题" 
            rules={[{ required: true, message: '请输入广告标题' }]}
          >
            <Input placeholder="请输入广告标题" />
          </Form.Item>
          
          <Form.Item 
            name="type" 
            label="广告类型" 
            rules={[{ required: true, message: '请选择广告类型' }]}
          >
            <Select placeholder="请选择广告类型">
              <Option value="轮播图">轮播图</Option>
              <Option value="弹窗">弹窗</Option>
              <Option value="横幅">横幅</Option>
              <Option value="推荐位">推荐位</Option>
            </Select>
          </Form.Item>
          
          <Form.Item 
            name="link" 
            label="广告链接" 
            rules={[{ required: true, message: '请输入广告链接' }]}
          >
            <Input placeholder="请输入广告链接" />
          </Form.Item>
          
          <Form.Item 
            name="date" 
            label="展示期" 
            rules={[{ required: true, message: '请选择展示期' }]}
          >
            <RangePicker 
              style={{ width: '100%' }} 
              format="YYYY-MM-DD"
              allowClear={true}
              disabledDate={(current) => {
                // 不能选择过去的日期
                return current && current < dayjs().startOf('day');
              }}
              // 设置年份选择范围
              picker="date"
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Ads; 